<template>
    <s-card title="密码修改">
      <s-form>
            <s-form-item label="当前密码">
               <s-input type="password" name="curPwd" :value="password.curPwd" @update="update" placeholder="请输入当前密码" :input-style="{width:'400px'}"/>
            </s-form-item>
            <s-form-item label="新密码">
               <s-input type="password" name="newPwd" :value="password.newPwd" @update="update" placeholder="8到32位(字母，数字，_，-，*), 需包含大小写字母,数字" :input-style="{width:'400px'}"/>
            </s-form-item>
            <s-form-item label="确认新密码">
               <s-input type="password" name="surePwd" :value="password.surePwd" @update="update" placeholder="8到32位(字母，数字，_，-，*), 需包含大小写字母,数字" :input-style="{width:'400px'}"/>
            </s-form-item>
         </s-form>
      <template #footer>
         <s-button type="primary" @click="handleSubmit">应用</s-button>
      </template>
   </s-card>
</template>

<script lang="ts" setup>
import { BaseForm } from "@types"
import { reactive } from "vue"
import { isPwd } from "@/utils"
import {
   SCard,
   SFormItem,
   SForm,
   SButton,
   Message,
   SInput
} from "@/components"
import { updatePwd } from "@/request"
import md5 from "md5"
import { useUser } from "@/hooks"
const { userInfo } = useUser()
const password = reactive({
   curPwd: "",
   newPwd: "",
   surePwd: ""
})

// 更新密码
const update = (param: BaseForm) => {
   password[param.name] = param.value
}
// 提交新密码
const handleSubmit = async () => {
   const { curPwd, surePwd, newPwd } = password
   if (curPwd === "") {
      return Message.error("当前密码不能为空")
   }
   if (newPwd !== surePwd) {
      return Message.error("新密码与确认密码不一致！")
   }

   if (!isPwd(newPwd) || !isPwd(surePwd)) {
      return Message.error("请输入8到32位(字母，数字，_，-，*), 需包含大小写字母,数字")
   }

   const res = await updatePwd({
      username: userInfo.value.username,
      oldpassword: md5(curPwd),
      newpassword: md5(newPwd)
   })

   if (res) {
      Message.success("修改成功！")
   }
}

</script>
